import cloud from '@lafjs/cloud'
let dbName = "admin-file"
const db = cloud.database();
const dbm = cloud.mongo.db
let docs = <any>[]  //所有用户数据
let userTags = []//学院标签

export default async function (ctx: FunctionContext) {
  let { type, data } = ctx.body

  docs = await dbm.collection('web-users').find({}).toArray()

  switch (type) {
    case "update":
      return update(data)
      break;
    case "downLoad":
      return downLoad(data)
      break;
    case "import":
      return importExcel(data)
      break;
    default:
      break;
  }
}

async function update(data) {
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { type: data["type"] },
  });
  if (res && res._id) {
    // 删除旧文件
    const bucketName = 'file' // 不带 Laf 应用 appid
    const Bucket = `dhkno3mf-${bucketName}`// 拼接文件桶名字
    await cloud.utils.ossDel(Bucket, res.path)
    await cloud.nw.db.update({
      dbName,
      whereJson: { type: data.type },
      dataJson: data
    });
  } else {
    await cloud.nw.db.add({
      dbName,
      dataJson: data,
      cancelAddTime: true
    });
  }
  return cloud.utils.requestReturn({ data: "" })
}

async function downLoad(data) {
  let resp = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { type: data["type"] },
  });
  return cloud.utils.requestReturn({ data: resp ? resp.path : "" })
}

function importExcel(data) {
  let { type, list } = data
  if (type == "student") {
    return studentImport(list)
  } else if (type == "order") {
    return orderImport(list)
  } else if (type == "invoice") {
    return invoiceImport(list)
  } else if (type == "studentUpdate") {
    return studentUpdateImport(list)
  } else if (type == "oldOrderImport") {
    return oldOrderImport(list)
  } else if (type == "orderIdCard") {
    return orderIdCard(list)
  } else if (type == "orderGraduation") {
    return orderGraduation(list)
  } else if (type == "orderProofWork") {
    return orderProofWork(list)
  }
}

//工作证明
async function orderProofWork(array) {
  let errList = <any>[]
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    let res = await cloud.nw.db.findByWhereJson({
      dbName: "web-order",
      whereJson: { out_trade_no: element.out_trade_no }
    });
    if (res && res.approvalContent) {
      let model = res.approvalContent
      let arr = []
      if (model.ProofWork) arr = [...model.ProofWork]
      if (arr.includes(element.url)) { } else {
        arr.push(element.url)
      }
      await cloud.nw.db.update({
        dbName: "web-order",
        whereJson: { out_trade_no: element.out_trade_no },
        dataJson: { "approvalContent.ProofWork": arr }
      });
    } else {
      element.res = res
      element.errText = "没有approvalContent"
      errList.push(element)
    }
  }
  return cloud.utils.requestReturn({ data: { errList } })
}

//订单毕业证导入
async function orderGraduation(array) {
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    let res = await cloud.nw.db.findByWhereJson({
      dbName: "web-order",
      whereJson: { out_trade_no: element.out_trade_no }
    });
    let model = res.approvalContent.model
    let arr = []
    if (model.certificate_scancopy) {
      let type = cloud.utils.isJsonArray(model.certificate_scancopy)
      if (type == "string") {
        arr = model.certificate_scancopy.split(',');
      } else if (type == "arr") {
        arr = model.certificate_scancopy
      } else {

      }
    }
    if (arr.includes(element.url)) { } else {
      arr.push(element.url)
    }
    await cloud.nw.db.update({
      dbName: "web-order",
      whereJson: { out_trade_no: element.out_trade_no },
      dataJson: {
        "approvalContent.model.certificate_scancopy": arr
      }
    });
  }
  return cloud.utils.requestReturn({ data: "" })
}

//订单身份证导入
async function orderIdCard(array) {
  let errList = <any>[]
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    let res = await cloud.nw.db.findByWhereJson({
      dbName: "web-order",
      whereJson: { out_trade_no: element.out_trade_no }
    });
    if (res && res.approvalContent && res.approvalContent.model) {
      let model = res.approvalContent.model
      let arr = []
      if (model.identification_scancopy) {
        let type = cloud.utils.isJsonArray(model.identification_scancopy)
        if (type == "string") {
          arr = model.identification_scancopy.split(',');
        } else if (type == "arr") {
          arr = model.identification_scancopy
        } else {

        }
      }
      if (arr.includes(element.url)) { } else {
        arr.push(element.url)
      }
      await cloud.nw.db.update({
        dbName: "web-order",
        whereJson: { out_trade_no: element.out_trade_no },
        dataJson: {
          "approvalContent.model.identification_scancopy": arr
        }
      });
    } else {
      element.errText = "没有approvalContent"
      element.res = res
      errList.push(element)
    }
  }
  return cloud.utils.requestReturn({ data: { errList } })
}

//历史订单导入
async function oldOrderImport(array) {
  let errList = <any>[]
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    let res = await cloud.nw.db.findByWhereJson({
      dbName: "web-order",
      whereJson: { out_trade_no: element.out_trade_no },
    });
    // console.log("xixi", element, res)
    if (res) {
      await cloud.nw.db.update({
        dbName: "web-order",
        whereJson: { out_trade_no: element.out_trade_no },
        dataJson: {
          updateUser: element.updateUser,
          dataForm: "file",
        }
      });
    } else {
      errList.push(element)
    }
  }
  return cloud.utils.requestReturn({ data: errList })
}

//学员信息导入编辑
async function studentUpdateImport(array) {
  let errList = <any>[]
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    let res = null
    let current = cloud.utils.findIndexByField(docs, "mobile", element.mobile)
    if (current != -1) res = docs[current]
    let hasStudentSource = await userSource(element.studentSourceList)
    if (!res) {
      element.errText = "手机号不存在"
      errList.push(element)
    }
    else if (res.baseInfo && res.baseInfo.identityCard && (res.baseInfo.identityCard != element.identityCard)) {
      element.errText = "身份证号不匹配"
      errList.push(element)
    }
    else if (cloud.utils.isString(hasStudentSource)) {
      element.errText = hasStudentSource
      errList.push(element)
    } else {
      element.studentSourceList = hasStudentSource
      let tags = element.tags
      if (tags != "/") element.tags = tags.split(',');
      let dataJson = { baseInfo: element, mobile: element.mobile, studentSourceList: hasStudentSource }
      if (element.updateUser) dataJson.baseInfo['updateUser'] = element.updateUser
      await cloud.nw.db.update({
        dbName: "web-users",
        whereJson: { _id: res._id },
        dataJson
      });
    }
  }
  return cloud.utils.requestReturn({ data: { errorList: errList } })
}

//学员信息导入
async function studentImport(array) {
  try {
    //学员标签字典
    let { data } = await cloud.nw.db.findByWhereJson({
      dbName: "dict",
      whereJson: { code: "user_tag" },
    });
    userTags = data

    let rights = <any>[]  //导入成功的数组
    let errDatas = <any>[]  //导入错误的数组

    for (let index = 0; index < array.length; index++) {
      const element = array[index];
      let resp = await checkUser(element)
      if (resp.errText) {
        errDatas.push(resp)
      } else {
        await cloud.nw.db.add({
          dbName: "web-users",
          dataJson: { baseInfo: element, mobile: element.mobile, studentSourceList: element.studentSourceList },
          cancelAddTime: false
        });
        rights.push(resp)
      }
    }
    return cloud.utils.requestReturn({ data: { errorList: errDatas, rights } })
  } catch (error) {
    console.log("error", error)
  }

  async function checkUser(element) {
    let hasStudentSource = await userSource(element.studentSourceList)

    let errText //错误提示

    //判断是否存在手机号
    let current = cloud.utils.findIndexByField(docs, "mobile", element.mobile)
    let identityCardInfo = null  //身份证是否存在
    for (let index = 0; index < docs.length; index++) {
      const item = docs[index];
      if (item.baseInfo && (item.baseInfo.identityCard == element.identityCard)) {
        identityCardInfo = item
      }
    }

    let tags = element.tags != "/" ? element.tags.split(",") : []

    if (cloud.utils.isString(hasStudentSource)) {
      errText = hasStudentSource
    } else if (current != -1) {
      errText = "手机号已存在"
    }
    else if (identityCardInfo && identityCardInfo._id) {
      errText = "身份证号已存在"
    } else if (tags.length) {
      for (let j = 0; j < tags.length; j++) {
        const item = tags[j];
        let current = cloud.utils.findIndexByField(userTags, 'dict_code', item)
        if (current == -1) {
          errText = `${item}标签字典不存在`
        }
      }
    }
    //如果没有错误提示
    if (errText) {
      element.errText = errText
    } else {
      element.tags = tags
      element.studentSourceList = hasStudentSource
    }
    return element
  }
}

async function userSource(studentSource) {
  if (!studentSource.length) return {}
  if (['/', '-'].includes(studentSource)) return {}
  let dictData = []
  let ret = await db.collection("dict").where({ code: "user_source" }).get()
  dictData = ret.data[0].data


  let arr = []
  if (studentSource.includes(",")) {
    arr = studentSource.split(",")
  } else if (studentSource.includes(";")) {
    arr = studentSource.split(";")
  } else {
    arr = studentSource.split(",")
  }

  let list = []
  for (let index = 0; index < arr.length; index++) {
    const element = arr[index];
    let res = await cloud.nw.db.findByWhereJson({
      dbName: "web-course",
      whereJson: { studentSource: element },
    });
    if (res && res._id) {
      list.push({ source: element, curriculumId: res._id })
    } else if (cloud.utils.isFieldEqual(dictData, 'dict_code', element)) {
      list.push({ source: element })
    }
    else {
      return `${element} - 该学员来源不存在`
    }
  }
  return list
}


//订单信息导入
async function orderImport(array) {
  let list = <any>[] //有问题的数据
  let rights = <any>[]  //导入成功的数组

  //所有课程
  let fieldJson = { needUserParams: 1, lessonContent: 1, name: 1, _id: 1 }
  let data = await dbm.collection("web-course")
    .find({})
    .project(fieldJson)// 过滤掉不需要的字段
    .toArray()

  //console.log("所有课程", data)

  let lessonContentData = <any>[] //所有课程内容
  let affiliationData = <any>[] //所有报名所属

  data.forEach(element => {
    if (element.needUserParams && element.needUserParams.length) {
      element.needUserParams.forEach(item => {
        if (item.fieldName == 'affiliation' && item.defaultValue) {
          let arr = item.defaultValue.split(",")
          affiliationData.push(...arr)
        }
      });
    }
    element.lessonContent.forEach(item => {
      lessonContentData.push(item)
    });
  });

  for (let index = 0; index < array.length; index++) {
    const element = array[index];

    //判断课程是否存在
    let res = null
    let idx = cloud.utils.findIndexByField(data, 'name', element.curriculum_name)
    if (idx != -1) {
      res = cloud.utils.deepcopy(data[idx])
    } else {
      console.log("课程不存在", element.curriculum_name)
    }


    let ret = null
    let current = cloud.utils.findIndexByField(docs, 'mobile', element.mobile)
    if (current != -1) ret = docs[current]

    //是否是当年的同一个课程 && 是否有这个课程
    let result
    let curriculum_year = cloud.utils.dateTimeFormat(element._add_time_str, "year")
    if (curriculum_year && res) {
      const startOfYear = new Date(curriculum_year, 0, 1).getTime(); // 该年份的开始时间戳
      const endOfYear = new Date(curriculum_year, 11, 31, 23, 59, 59, 999).getTime(); // 该年份的结束时间戳
      result = await cloud.nw.db.findByWhereJson({
        dbName: "web-order",
        whereJson: {
          _add_time: { $gt: startOfYear, $lt: endOfYear },
          curriculum_id: res._id,
          approvalContent: {
            model: {
              mobile: element.mobile,
              identityCard: element.identityCard,
            }
          }
        },
      });
    }


    //判断是否有课程内容错误
    let checkLessonIsError = checkLesson(element.selectLesson)
    if (cloud.utils.isString(checkLessonIsError)) {  //如果是字符串，这是有问题
      element.errText = checkLessonIsError
      list.push(element)
    }
    else if (affiliationData.length && element.affiliation && (!affiliationData.includes(element.affiliation))) {
      element.errText = `报名所属非标准值`
      list.push(element)
    } else if (!res) {
      element.errText = `课程不存在`
      list.push(element)
    } else if (!ret) {
      element.errText = `该手机号的用户不存在`
      list.push(element)
    } else if (ret.baseInfo.identityCard != element.identityCard) {
      element.errText = `该手机号的用户对应的身份证号不匹配`
      list.push(element)
    }
    else if (result && result._id) {
      element.errText = `同一个课程不可重复报名`
      list.push(element)
    } else {
      let obj = {
        approvalContent: {
          model: {
            name: element.name,
            mobile: element.mobile,
            identityCard: element.identityCard,
            affiliation: element.affiliation,
            graduationMajor: element.graduationMajor,
            workYears: element.workYears,
            email: element.email,
            education: element.education,
            enterprise: element.enterprise,
            enterpriseTax: element.enterpriseTax,
            enterpriseJurisdiction: element.enterpriseJurisdiction,
          },
          "relationList": [],
          selectLesson: checkLessonIsError
        },
        curriculum_id: res._id,
        price: element.price,
        "payType": "MP-WEIXIN",
        "status": 2,
        _add_time_str: element._add_time_str,
        _add_time: element._add_time ? element._add_time : cloud.utils.getTimeFn(element._add_time_str),
        userId: ret._id,
        out_trade_no: generateOrderNumber(),//订单号
        mobile: element.mobile,
      }
      if (element.updateUser) obj["updateUser"] = element.updateUser
      if (element.dataForm) obj["dataForm"] = element.dataForm
      rights.push(obj)
    }
  }

  function checkLesson(e) {
    let list = <any>[]
    if (!e) return []
    let array = e.split(",")
    for (let index = 0; index < array.length; index++) {
      const element = array[index];
      let current = cloud.utils.findIndexByField(lessonContentData, 'name', element)
      if (current != -1) {
        list.push(lessonContentData[current])
      } else {
        return `${element} - 该课程内容不存在`
      }
    }
    return list
  }

  //检查订单号有没有重复的
  let repeatList = generateUniqueFieldValue(rights, 'out_trade_no', generateOrderNumber)
  if (repeatList.length) {  //新增订单
    for (let index = 0; index < repeatList.length; index++) {
      const element = repeatList[index];
      await cloud.nw.db.add({
        dbName: "web-order",
        dataJson: element,
        cancelAddTime: true
      });
    }
  }

  return cloud.utils.requestReturn({ data: { errorList: list, successList: repeatList } })
}

// 生成订单号
function generateOrderNumber() {
  const timestamp = Date.now().toString(); // 获取当前时间戳
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0'); // 生成3位随机数
  return timestamp + random; // 拼接时间戳和随机数作为订单号
}

//传入数组和字段名，如果该字段的值是重复的，则重新生成值，直到不重复
function generateUniqueFieldValue(array: Array<any>, fieldName: string, generateNewValue: () => any): Array<any> {
  const existingValues = new Set(array.map(item => item[fieldName]));

  return array.map(item => {
    let newValue = item[fieldName];

    // 如果当前值已存在，则生成新值直到不重复
    while (existingValues.has(newValue)) {
      newValue = generateNewValue(); // 生成新值
    }

    // 更新当前项的字段值
    item[fieldName] = newValue;
    existingValues.add(newValue); // 将新值添加到集合中
    return item;
  });
}


//发票导入
async function invoiceImport(array) {
  let errorList = <any>[] //有问题的数据
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    let res = await cloud.nw.db.findByWhereJson({
      dbName: "web-order",
      whereJson: { out_trade_no: element.ddlsh },
    });
    let ret = await cloud.nw.db.findByWhereJson({
      dbName: "invoicing",
      whereJson: { ddlsh: element.ddlsh },
    });
    if (ret && ret._id) {
      element.errText = `该订单已开发票`
      errorList.push(element)
    }
    else if (res && res._id) {
      await cloud.nw.db.add({
        dbName: "invoicing",
        dataJson: element,
        cancelAddTime: false
      });
    } else {
      element.errText = `订单号不存在`
      errorList.push(element)
    }
  }
  if (errorList.length) {
    return cloud.utils.requestReturn({ data: errorList })
  } else {
    return cloud.utils.requestReturn({ data: "" })
  }
}


